package com.wuwei.elearning.utils.word;

import com.wuwei.elearning.exception.ElearningMysqlException;
import com.wuwei.elearning.question.domain.QuestionTranslated;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@Component
public class WordUtils {

    public void writeToBeDocxForTable( List<QuestionTranslated> questionTranslatedList) {
        String templatePath = "template-en.docx";
        String wordPath = "word.docx";
        try {
            File file = new File(templatePath);
            if (!file.exists()) {
                throw new ElearningMysqlException(30011, "请检查模板文件是否存在！");
            }
            InputStream is = Files.newInputStream(Paths.get(templatePath));
            XWPFDocument document = new XWPFDocument(is);

            //设置考卷信息
            List<XWPFParagraph> paragraphs = document.getParagraphs();
            XWPFParagraph paragraph = paragraphs.get(1);
            paragraph.getRuns().get(0).setBold(true);

            XWPFTable table = document.createTable(1, 2);
            table.setWidth("100%");
            // Set column widths (each column 50%)
            CTTblLayoutType tblLayout = table.getCTTbl().getTblPr().addNewTblLayout();
            tblLayout.setType(STTblLayoutType.FIXED);
            setTableBorders(table);

            for (int col = 0; col < 2; col++) {
                CTTblGridCol tblCol = table.getCTTbl().addNewTblGrid().addNewGridCol();
                tblCol.setW(BigInteger.valueOf(5000)); // Adjust the width as necessary
            }

            //插入第一道题目
            QuestionTranslated questionTranslated0 = questionTranslatedList.get(0);
            XWPFTableCell cell0 = table.getRow(0).getCell(0);
//            extracted(cell0, "1." + question0.getQuestion(), "1." + questionTranslated0.getQuestion());
            cell0.setText("1." +questionTranslated0.getQuestion());
            mergeCellsHorizontally(table,0,0,1);
            int rowNum = 1;
            rowNum = setInnerQuestion(questionTranslated0, table, rowNum);
            table.createRow();
            rowNum++;
            int questionNum = 2;

            //插入后面的题目
            for (int i = 1; i < questionTranslatedList.size(); i++) {
                QuestionTranslated questionTranslated = questionTranslatedList.get(i);
                XWPFTableRow row = table.createRow();
                rowNum++;
                row.getCell(0).setText(questionNum + "." + questionTranslated.getQuestion());
//                extracted(row.getCell(0),  questionNum + "." + question.getQuestion(), "  " + questionTranslated.getQuestion());
                mergeCellsHorizontally(table,rowNum-1,0,1);
                questionNum++;
                rowNum = setInnerQuestion( questionTranslated, table, rowNum);
                table.createRow();
                rowNum++;
            }

            //设置答案
            setAnswer(document,questionTranslatedList);
            //Save the document
            FileOutputStream outputStream1 = new FileOutputStream(wordPath);
            document.write(outputStream1);
            outputStream1.close();
            document.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int setInnerQuestion( QuestionTranslated questionTranslated, XWPFTable table, int rowNum) {
        //如果答案比较长，则答案表格变成4行
        if (questionTranslated.getItem1().length()>35|| questionTranslated.getItem2().length()>35|| questionTranslated.getItem3().length()>35|| questionTranslated.getItem4().length()>35
        ) {
            XWPFTableRow row1 = table.createRow();
            XWPFTableRow row2 = table.createRow();
            XWPFTableRow row3 = table.createRow();
            XWPFTableRow row4 = table.createRow();
            rowNum +=4;
            row1.getCell(0).setText("A."+ questionTranslated.getItem1());
            row2.getCell(0).setText("B."+ questionTranslated.getItem2());
            row3.getCell(0).setText("C."+ questionTranslated.getItem3());
            row4.getCell(0).setText("D."+ questionTranslated.getItem4());

//            extracted(row1.getCell(0),"A."+ question.getItem1()," "+ questionTranslated.getItem1());
//            extracted(row2.getCell(0),"B."+ question.getItem2()," "+ questionTranslated.getItem2());
//            extracted(row3.getCell(0),"C."+ question.getItem3()," "+ questionTranslated.getItem3());
//            extracted(row4.getCell(0),"D."+ question.getItem4()," "+ questionTranslated.getItem4());
            mergeCellsHorizontally(table, rowNum -1,0,1);
            mergeCellsHorizontally(table, rowNum -2,0,1);
            mergeCellsHorizontally(table, rowNum -3,0,1);
            mergeCellsHorizontally(table, rowNum -4,0,1);
        }
//                否则答案表格变成2行
        else {
            XWPFTableRow row1 = table.createRow();
            XWPFTableRow row2 = table.createRow();
            rowNum +=2;
            row1.getCell(0).setText("A."+ questionTranslated.getItem1());
            row1.getCell(1).setText("B."+ questionTranslated.getItem2());
            row2.getCell(0).setText("C."+ questionTranslated.getItem3());
            row2.getCell(1).setText("D."+ questionTranslated.getItem4());


//            extracted(row1.getCell(0),"A."+ question.getItem1()," "+ questionTranslated.getItem1());
//            extracted(row1.getCell(1),"B."+ question.getItem2()," "+ questionTranslated.getItem2());
//            extracted(row2.getCell(0),"C."+ question.getItem3()," "+ questionTranslated.getItem3());
//            extracted(row2.getCell(1),"D."+ question.getItem4()," "+ questionTranslated.getItem4());
        }
        return rowNum;
    }

    /**
     * 设置答案
     * @param document
     * @param setQuestionList
     */
    private void setAnswer(XWPFDocument document, List<QuestionTranslated> setQuestionList) {
        document.createParagraph().createRun().setText("\n");

        String text =  "----------------------------------------------------------后面的为答案----------------------------------------------------------";
        document.createParagraph().createRun().setText(text);

        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < setQuestionList.size(); i++) {
            QuestionTranslated question = setQuestionList.get(i);
            String answer = question.getAnswer();
            builder.append(i+1+"."+answer+"   ");
        }
        document.createParagraph().createRun().setText(builder.toString());
    }

    private static void extracted(XWPFTableCell row, String string1, String string2) {
        XWPFParagraph paragraphArr = row.getParagraphArray(0);
        if (paragraphArr == null) paragraphArr = row.addParagraph();
        XWPFRun run1 = paragraphArr.createRun();
        run1.setText(string1);
        run1.addBreak();
        run1.setText(string2);
    }


    // 方法用于水平合并单元格
    private void mergeCellsHorizontally(XWPFTable table, int row, int fromCol, int toCol) {
        for (int colIndex = fromCol; colIndex <= toCol; colIndex++) {
            XWPFTableCell cell = table.getRow(row).getCell(colIndex);
            if ( colIndex == fromCol ) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * 取消表格的边框
     * @param table
     */
    private void setTableBorders(XWPFTable table) {
        // 设置表格的边框为0，即隐藏所有边框
        CTTblBorders tblBorders = table.getCTTbl().getTblPr().addNewTblBorders();
        tblBorders.addNewBottom().setVal(STBorder.NONE);
        tblBorders.addNewTop().setVal(STBorder.NONE);
        tblBorders.addNewLeft().setVal(STBorder.NONE);
        tblBorders.addNewRight().setVal(STBorder.NONE);
        tblBorders.addNewInsideH().setVal(STBorder.NONE);
        tblBorders.addNewInsideV().setVal(STBorder.NONE);
    }
}
